package org.esti.controller;

import org.esti.model.Level;
import org.esti.service.LevelService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.validation.Valid;
import java.util.Collection;
import java.util.logging.Logger;

/**
 * @author ALoginov <a href="mailto:Artem.Loginov@exigenservices.com">Artem Loginov</a>
 * @since 10/25/11
 */
@Controller
public class LevelController {

    private static final Logger LOGGER = Logger.getLogger(LevelController.class.getName());

    @Autowired
    private LevelService levelService;

    @RequestMapping(value = "/levels")
    public String showLevels(Model model) {

        Collection<Level> levels = levelService.getAllLevels();

        model.addAttribute("levels", levels);

        return "levels";
    }

    @RequestMapping(value = "/levels", params = "action=add", method = RequestMethod.GET)
    public String showAddLevelForm(Model model) {

        model.addAttribute("level", new org.esti.model.Level());

        return "add_level";
    }

    @RequestMapping(value = "/levels", params = "action=add", method = RequestMethod.POST)
    public String processAddLevelForm(
            @ModelAttribute @Valid org.esti.model.Level level,
            BindingResult bindingResult, Model model) {

        if (bindingResult.hasErrors()) {
            LOGGER.log(java.util.logging.Level.INFO, "add level form is not valid");
            return "redirect:/";
        }

        levelService.add(level);

        return "redirect:/levels?action=add";
    }

    @RequestMapping(value = "/levels/{id}", params = "action=delete")
    public String removeLevel(
            @PathVariable long id
    ) {

        levelService.remove(id);

        return "redirect:/levels";
    }
}